import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class WordToPdfConverter {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("output.docx");
             FileOutputStream fos = new FileOutputStream("output2.pdf");
             XWPFDocument document = new XWPFDocument(fis)) {

            Document pdfDocument = new Document();
            PdfWriter.getInstance(pdfDocument, fos);
            pdfDocument.open();

            // 读取Word文档中的段落内容并写入PDF
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                for (XWPFRun run : paragraph.getRuns()) {
                    String text = run.getText(0);
                    if (text != null) {
                        Paragraph pdfParagraph = new Paragraph(text);
                        pdfDocument.add(pdfParagraph);
                    }
                }
            }

            pdfDocument.close();

            System.out.println("PDF created successfully.");

        } catch (IOException e) {
            e.printStackTrace();
        } catch (com.itextpdf.text.DocumentException e) {
            e.printStackTrace();
        }
    }
}
